/*
 * @Description: 我的申请列表
 * @Author: Rfan
 * @Date: 2023-02-10 11:12:19
 * @LastEditTime: 2023-02-28 11:03:59
 */

import { useEffect, useMemo, useState } from 'react';
import { Button, Space, Table, Tag } from 'antd';
import classNames from 'classnames/bind';
import update from 'immutability-helper';
import { useFormatMessage } from '@/utils/intlHelpers';
import { appState } from '@/store/mobx';
import { useMyApplyContext } from '../contexts/MyApplyContext';
import ProcessDialog from '../components/dialogs/ProcessDialog';
import type { MouseEvent } from 'react';
import type { IPageQuery } from '@/interfaces/global';
import type { IStartAuditProps } from '@/api/workFlow/task';
import styles from '../styles/list.module.scss';
import { ITaskProcessResolve } from '@/api/workFlow/task';

const cx = classNames.bind(styles);

const { Column } = Table;

export type ApplyTableProps = {
  title?: string;
  data?: any;
};

const ApplyTable = (props: ApplyTableProps) => {
  const formatMessage = useFormatMessage();
  const {
    approveList,
    listQuery,
    setListQuery,
    setArcList,
    getApproveList,
    showFlowNodeDialog,
    startTaskFunc,
    stateFilter
  } = useMyApplyContext();
  // 列表选中的条目
  const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);
  // 列表加载状态
  const [loading, setLoading] = useState(false);
  // 全部条目数
  const [total, setTotal] = useState(0);
  // 选中的条目
  const [selectProcess, setSelectProcess] = useState<ITaskProcessResolve>(null);
  // 详情弹窗标志
  const [processDialogFlag, setProcessDialogFlag] = useState(false);

  /**
   * @description: 参数变更，如切换页面请求列表
   */
  useEffect(() => {
    setLoading(true);
    getApproveList(listQuery)
      .then((res: any) => {
        setTotal(res?.totalCount);
      })
      .finally(() => {
        setLoading(false);
      });
  }, [listQuery]);

  /**
   * @description: 切换页码触发
   * @param {number} page 选中的页码
   * @param {number} pageSize 请求的条目数
   */
  const pageChange = (page: number, pageSize: number) => {
    setListQuery(
      update(listQuery, {
        $apply: (state: IPageQuery) => ({
          ...state,
          pageNo: page,
          pageSize
        })
      })
    );
  };

  /**
   * @description: 案卷列表选中条目方法
   * @param {any} record 选中的条目
   */
  const selectRow = (record: any) => {
    const _selectedRowKeys = [...selectedRowKeys];
    if (_selectedRowKeys.indexOf(record.id) < 0) {
      setSelectedRowKeys([record.id]);
      setArcList(record.id);
    }
  };

  /**
   * @description: 点击查看按钮展示弹窗
   * @param {MouseEvent} evt 点击事件
   * @param {any} item 条目信息
   * @return {*}
   */
  const showProcessModal = (evt: MouseEvent, item: any): void => {
    evt.stopPropagation();
    showFlowNodeDialog(item.processInstanceId).then((data: any) => {
      setSelectProcess(data);
      setProcessDialogFlag(true);
    });
  };
  /**
   * @description: 点击查看按钮展示弹窗
   * @param {any} item 条目信息
   */
  const submitAudit = (item: any): void => {
    const param: IStartAuditProps = {
      businessKey: item.applyFormNo,
      identity: appState.userInfo.id,
      modelType: 'JIE_YUE_FLOW'
    };
    startTaskFunc(param);
  };

  return (
    <div className={cx('apply-table')}>
      <Table
        dataSource={approveList || []}
        loading={loading}
        rowKey="id"
        bordered
        onRow={(record) => ({
          onClick: () => {
            selectRow(record);
          }
        })}
        pagination={{
          current: listQuery.pageNo,
          pageSize: listQuery.pageSize,
          total,
          onChange: pageChange
        }}
      >
        <Column title="申请单号" dataIndex="applyFormNo" key="applyFormNo" align="center" />
        <Column
          title="申请单名称"
          dataIndex="processDefinitionName"
          key="processDefinitionName"
          align="center"
        />
        <Column title="开始时间" dataIndex="startTime" key="startTime" align="center" />
        <Column
          title="状态"
          dataIndex="taskState"
          key="taskState"
          align="center"
          render={(text) => <Tag>{stateFilter(text)}</Tag>}
        />
        {/* <Column title="全宗" dataIndex="fondsName" key="fondsName" align="center" /> */}
        {/* <Column title="利用目的" dataIndex="purpose" key="purpose" align="center" /> */}
        {/* <Column title="实体利用申请" dataIndex="useTypeEntity" key="useTypeEntity" align="center" /> */}
        {/* <Column */}
        {/*  title="电子利用申请" */}
        {/*  dataIndex="useTypeElectronicRights" */}
        {/*  key="useTypeElectronicRights" */}
        {/*  align="center" */}
        {/* /> */}
        <Column
          title={formatMessage('tableAction')}
          key="action"
          align="center"
          render={(_text, record: any) => (
            <Space>
              <Button
                type="link"
                onClick={(evt) => {
                  showProcessModal(evt, record);
                }}
              >
                查看流程
              </Button>
            </Space>
          )}
        />
      </Table>

      {useMemo(
        () =>
          selectProcess && (
            <ProcessDialog
              visible={processDialogFlag}
              data={selectProcess}
              onClose={() => {
                setProcessDialogFlag(false);
              }}
            />
          ),
        [processDialogFlag]
      )}
    </div>
  );
};

export default ApplyTable;
